package com.zjq.authoritysystem.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zjq.authoritysystem.vo.result.Result;
import com.zjq.authoritysystem.vo.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * AuthenticationEntryPoint（身份验证入口点）是一个接口，用于定义在需要身份验证的资源被访问时如何处理未经身份验证的请求。
 * 当用户尝试访问受保护的资源但未提供有效的身份验证凭证时，AuthenticationEntryPoint负责决定返回什么样的响应给客户端。
 *
 * @author Kimiaaaaa
 * @className AnonymousAuthenticationHandler
 * @Description 匿名用户访问无权限资源处理器
 * @date 2023-09-19 15:45
 */
@Slf4j
@Component
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.info("-------------匿名用户访问无权限资源处理器启动");
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        String result = JSON.toJSONString(Result.Error(ResultCode.NO_LOGIN.getCode(), "请先登录！"),
                SerializerFeature.DisableCircularReferenceDetect);
        log.info("处理信息：" + result);
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        log.info("-------------匿名用户访问无权限资源处理器结束");
    }
}
